package com.wgchao.authmanager.application.service;

import com.wgchao.authmanager.domain.model.Agency;
import com.wgchao.authmanager.domain.params.AgencyCreator;
import com.wgchao.authmanager.domain.params.AgencyUpdator;
import com.wgchao.authmanager.domain.repository.AgencyRepository;
import com.wgchao.authmanager.infrastructure.exception.ObjectNotExistException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @作者：wgchao
 * @时间：21:54 2020/4/25 0025
 * @用途： 机构（应用服务）
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class AgencyService {
    @Autowired
    private AgencyRepository agencyRepository;

    /**
     * 新建机构
     * @param creator
     * @param operator
     */
    public void addNewAgency(AgencyCreator creator, String operator){
        String agencyCode = agencyRepository.geneteAgencyCode();
        Agency agency = Agency.addNewAgency(agencyCode, creator, operator);
        agencyRepository.add(agency);
    }

    /**
     * 修改机构基本信息
     * @param agencyCode
     * @param agencyUpdator
     * @param operator
     */
    public void reviseAgencyInfo(String agencyCode, AgencyUpdator agencyUpdator, String operator){
        Agency agency = agencyRepository.get(agencyCode);
        if(agency == null){
            throw new ObjectNotExistException("机构不存在");
        }
        agency.reviseInfo(agencyUpdator, operator);
        agencyRepository.add(agency);
    }

    /**
     * 停用机构
     * @param agencyCode
     * @param operator
     */
    public void stopUsingAgency(String agencyCode, String operator){
        Agency agency = agencyRepository.get(agencyCode);
        if(agency == null){
            throw new ObjectNotExistException("机构不存在");
        }
        agency.stopUsing(operator);
        agencyRepository.add(agency);
    }

    /**
     * 重新启用机构
     * @param agencyCode
     * @param operator
     */
    public void reEnableAgency(String agencyCode, String operator){
        Agency agency = agencyRepository.get(agencyCode);
        if(agency == null){
            throw new ObjectNotExistException("机构不存在");
        }
        agency.reEnable(operator);
        agencyRepository.add(agency);
    }

    /**
     * 删除机构
     * @param agencyCode
     * @param operator
     */
    public void removeAgency(String agencyCode, String operator){
        Agency agency = agencyRepository.get(agencyCode);
        if(agency == null){
            throw new ObjectNotExistException("机构不存在");
        }
        agencyRepository.remove(agency, operator);
    }
}
